package com.zf.shuashua.video;

import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.FrameLayout;
import android.widget.ProgressBar;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;

import com.aliyun.apsara.alivclittlevideo.R;
import com.aliyun.apsara.alivclittlevideo.net.data.LittleMineVideoInfo;
import com.aliyun.apsara.alivclittlevideo.view.video.BaseVideoSourceModel;
import com.aliyun.apsara.alivclittlevideo.view.video.OnStsInfoExpiredListener;
import com.aliyun.apsara.alivclittlevideo.view.video.videolist.AlivcVideoListView;
import com.aliyun.apsara.alivclittlevideo.view.video.videolist.IVideoSourceModel;
import com.aliyun.apsara.alivclittlevideo.view.video.videolist.OnTimeExpiredErrorListener;
import com.aliyun.player.AliListPlayer;
import com.aliyun.player.IPlayer;
import com.aliyun.player.nativeclass.TrackInfo;
import com.aliyun.svideo.base.sts.StsTokenInfo;
import com.lxj.xpopup.XPopup;
import com.zf.shuashua.bean.AdvertInfo;
import com.zf.shuashua.ui.home.InterestPopup;
import com.zf.shuashua.ui.mine.FriendsDetailsActivity;
import com.zf.shuashua.ui.mine.LogUtil;

import java.util.ArrayList;
import java.util.List;


/**
 * 播放界面, 负责initPlayerSDK以及各种view
 *
 * @author xlx
 */
public class AlivcVideoPlayView extends FrameLayout {

    private static final String TAG = "AlivcVideoPlayView";
    private Context context;
    private AlivcVideoListView videoListView;

    /**
     * 刷新数据listener (下拉刷新和上拉加载)
     */
    private AlivcVideoListView.OnRefreshDataListener onRefreshDataListener;

    /**
     * 视频缓冲加载view
     */
//    private LoadingView mLoadingView;

    private ProgressBar mPlayProgressBar;

    /**
     * 视频删除点击事件
     */
    private OnVideoDeleteListener mOutOnVideoDeleteListener;
    private LittleVideoListAdapter mVideoAdapter;
    private OnItemClickListener mOnClickListener;

    private long currentTime;
    private long currentProgress;
    private ValueAnimator progressAnimator;

    public AlivcVideoPlayView(@NonNull Context context) {
        this(context, null);
    }

    public AlivcVideoPlayView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        init();
    }

    private void init() {
        initPlayListView();
        initLoadingView();
        initPlayProgressBar();
    }

    public void closeRefresh() {
        if (videoListView != null) {
            videoListView.closeRefresh();
        }
    }

    public BaseVideoSourceModel getCurrentModel() {
        try {
            if (mVideoAdapter != null && mVideoAdapter.getDataList() != null && mVideoAdapter.getDataList().size() > 0 && videoListView != null) {
                return mVideoAdapter.getDataList().get(videoListView.getCurrentPosition());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return null;
    }

    private int mClickPosition;

    public boolean isPause() {
        return videoListView != null && videoListView.isPause();
    }

    public AliListPlayer getPlayer() {
        return videoListView.getPlayer();
    }


    public int getIndex() {
        return videoListView.getCurrentPosition();
    }

    /**
     * 初始化视频列表
     */
    private void initPlayListView() {
        videoListView = new AlivcVideoListView(context);
        //创建adapter，需要继承BaseVideoListAdapter
        mVideoAdapter = new LittleVideoListAdapter(context);
        mVideoAdapter.setItemBtnClick(new LittleVideoListAdapter.OnItemBtnClick() {
            @Override
            public void onDownloadClick(int position) {
            }

            @Override
            public void onJumpComment(String videoId, String headerUrl, int commentCount, int position) {
                if (mOnClickListener != null) {
                    mOnClickListener.onJumpComment(videoId, headerUrl, commentCount, position);
                }
            }

            @Override
            public void onJumpShare() {
                if (mOnClickListener != null) mOnClickListener.onJumpShare();
            }

            @Override
            public void onAdPlayStart() {
                LogUtil.d("onAdPlayStart");
                if (getOnPlayStatusListener() != null) {
                    getOnPlayStatusListener().start();
                }
                if (mOnClickListener != null) {
                    mOnClickListener.onAdPlayStart();
                }
            }

            @Override
            public void onAdPlayPaused() {
                LogUtil.d("onAdPlayPaused");
                if (getOnPlayStatusListener() != null) {
                    getOnPlayStatusListener().stop(null, -1);
                }
                if (mOnClickListener != null) {
                    mOnClickListener.onAdPlayPaused();
                }
            }

            @Override
            public void onAdPlayComplete() {
                LogUtil.d("onAdPlayComplete");
                if (getOnPlayStatusListener() != null) {
                    getOnPlayStatusListener().onCompletion();
                }
                if (mOnClickListener != null) {
                    mOnClickListener.onAdPlayComplete();
                }
            }

            @Override
            public void onJumpAdDetail(String link_type, String url) {
                if (mOnClickListener != null) mOnClickListener.onJumpAdDetail(link_type, url);
            }

            @Override
            public void onPauseVideo() {
                if (videoListView != null) {
                    videoListView.onPauseClick();
                }
            }
        });

        //给AlivcVideoListView实例化对象添加adapter
        videoListView.setAdapter(mVideoAdapter);
        videoListView.setOnAdPlayListener(new AlivcVideoListView.OnAdPlayListener() {
            @Override
            public boolean isAdStart() {
                if (mVideoAdapter != null) {
                    return mVideoAdapter.isAdStart();
                }
                return false;
            }
        });
        videoListView.setVisibility(VISIBLE);
        //设置sdk播放器实例化对象数量
        videoListView.setPlayerCount(5);
        //设置下拉、上拉监听进行加载数据
        videoListView.setOnRefreshDataListener(new AlivcVideoListView.OnRefreshDataListener() {
            @Override
            public void onRefresh() {
                if (onRefreshDataListener != null) {
                    onRefreshDataListener.onRefresh();
                }
            }

            @Override
            public void onLoadMore() {
                if (onRefreshDataListener != null) {
                    onRefreshDataListener.onLoadMore();
                }
            }
        });
        //设置视频缓冲监听
        videoListView.setLoadingListener(new IPlayer.OnLoadingStatusListener() {
            @Override
            public void onLoadingBegin() {
//                mLoadingView.start();
                if (mPlayProgressBar != null) {
                    mPlayProgressBar.setVisibility(GONE);
                }
            }

            @Override
            public void onLoadingEnd() {
//                mLoadingView.cancle();
            }

            @Override
            public void onLoadingProgress(int var1, float var2) {

            }
        });
        //设置鉴权过期监听，刷新鉴权信息
        videoListView.setTimeExpiredErrorListener(new OnTimeExpiredErrorListener() {

            @Override
            public void onTimeExpiredError() {
                if (mStsInfoExpiredListener != null) {
                    mStsInfoExpiredListener.onTimeExpired();
                }
            }
        });
        videoListView.setOnPlayProgressListener(new AlivcVideoListView.OnPlayProgressListener() {
            @Override
            public void onPlayProgress(long progress, long all) {
                if (mPlayProgressBar != null) {
                    mPlayProgressBar.setVisibility(VISIBLE);
                    mPlayProgressBar.setMax(Integer.parseInt(all + ""));
                    long animDuration = System.currentTimeMillis() - currentTime;
                    if (animDuration <= 0) {
                        animDuration = 0;
                    }
                    if (animDuration > 1000) {
                        mPlayProgressBar.setProgress(Integer.parseInt(progress + ""));
                    } else {
                        if (progressAnimator != null && progressAnimator.isRunning()) {
                            progressAnimator.end();
                        }
                        progressAnimator = ValueAnimator.ofInt((int) currentProgress, (int) progress);
                        progressAnimator.setDuration(animDuration);
                        progressAnimator.setInterpolator(new LinearInterpolator());
                        progressAnimator.addUpdateListener(animation -> {
                            int value = (int) animation.getAnimatedValue();
                            mPlayProgressBar.setProgress(value);
                        });
                        progressAnimator.start();
                    }
                    currentProgress = progress;
                    currentTime = System.currentTimeMillis();
                }
            }
        });
        videoListView.setOnGestureDetectorListener(e -> new XPopup.Builder(getContext())
                .asCustom(new InterestPopup(getContext(), () -> {
                    if (mVideoAdapter != null && mVideoAdapter.getDataList() != null && mVideoAdapter.getDataList().size() > 0 && videoListView != null) {
                        videoListView.removeCurrentPlayVideo();
                    }
                }))
                .show());

        videoListView.setOnViewPagerListener(position -> {
            if (mViewPagerListener != null) mViewPagerListener.onPageSelected(position);
        });

        //添加到布局中
        addSubView(videoListView);
    }

    private OnViewPagerListener mViewPagerListener;

    public interface OnViewPagerListener {
        void onPageSelected(int position);
    }

    public void setOnViewPagerListener(OnViewPagerListener listener) {
        this.mViewPagerListener = listener;
    }

    public boolean isRefreshing() {
        if (videoListView != null) {
            return videoListView.isRefreshing();
        }
        return false;
    }

    public void onRefresh() {
        if (videoListView != null) {
            videoListView.onRefresh();
        }
    }

    /**
     * 播放、下载、上传过程中鉴权过期时提供的回调消息
     */
    private OnStsInfoExpiredListener mStsInfoExpiredListener;

    public void setOnStsInfoExpiredListener(
            OnStsInfoExpiredListener mTimeExpiredErrorListener) {
        this.mStsInfoExpiredListener = mTimeExpiredErrorListener;
    }

    /**
     * 获取视频质量最高的视频
     *
     * @param list
     * @return
     */
    private int pickDownloadQualityMedia(List<TrackInfo> list) {
        int index = 0;
        for (int i = 0; i < list.size(); i++) {
            TrackInfo trackInfo = list.get(i);
            if ("LD".equals(trackInfo.getVodDefinition())) {
                index = trackInfo.getIndex();
            }
        }
        return index;
    }

    private void initLoadingView() {
//        mLoadingView = new LoadingView(context, LoadingView.DEFAULT_START_MODE_CENTER);
//        LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,
//                5);
//        params.setMargins(0, 0, 0, DensityUtil.dip2px(getContext(), 10));
//        params.gravity = Gravity.BOTTOM;
//        addView(mLoadingView, params);
    }

    private void initPlayProgressBar() {
        mPlayProgressBar = (ProgressBar) LayoutInflater.from(context).inflate(R.layout.play_progress_bar, null);
        LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,
                2);
        params.gravity = Gravity.BOTTOM;
        mPlayProgressBar.setVisibility(GONE);
        addView(mPlayProgressBar, params);
    }

    /**
     * addSubView 添加子view到布局中
     *
     * @param view 子view
     */
    private void addSubView(View view) {
        LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT);
        addView(view, params);
    }

    /**
     * 刷新视频列表数据
     *
     * @param datas
     */
    public void refreshVideoList(List<? extends BaseVideoSourceModel> datas) {
        List<IVideoSourceModel> videoList = new ArrayList<>();
        videoList.addAll(datas);
        videoListView.refreshData(videoList);
        //取消加载loading
//        mLoadingView.cancle();

    }

    /**
     * 刷新视频列表数据
     *
     * @param datas
     * @param position
     */
    public void refreshVideoList(List<LittleMineVideoInfo.VideoListBean> datas, int position) {
        if (videoListView != null) {
            List<IVideoSourceModel> videoList = new ArrayList<>();
            videoList.addAll(datas);
            videoListView.refreshData(videoList, position);
        }
        //取消加载loading
//        mLoadingView.cancle();


    }

    public List<IVideoSourceModel> getData() {
        return videoListView.getData();
    }

    public AlivcVideoListView getVideoListView() {
        return videoListView;
    }

    public LittleVideoListAdapter getAdapter() {
        return mVideoAdapter;
    }

    /**
     * 添加更多视频
     *
     * @param datas
     */
    public void addMoreData(List<? extends BaseVideoSourceModel> datas) {
        if (videoListView != null) {
            List<IVideoSourceModel> videoList = new ArrayList<>();
            videoList.addAll(datas);
            videoListView.addMoreData(videoList);
        }
        //取消加载loading
//        mLoadingView.cancle();
    }

    public void addAdPlayer(BaseVideoSourceModel model) {
        videoListView.addAdPlayer(model);
    }

    /**
     * 设置下拉刷新数据listener
     *
     * @param listener OnRefreshDataListener
     */
    public void setOnRefreshDataListener(AlivcVideoListView.OnRefreshDataListener listener) {
        this.onRefreshDataListener = listener;
    }

    public void onStart() {
    }

    public void showLoading() {
//        mLoadingView.start();
    }

    public void onResume() {
        if (videoListView == null) {
            return;
        }
        if (mVideoAdapter != null && mVideoAdapter.getCurrentHolder() != null && mVideoAdapter.getCurrentHolder().getCurrentModel() != null) {
            mVideoAdapter.onResume();
            BaseVideoSourceModel currentModel = mVideoAdapter.getCurrentHolder().getCurrentModel();
            if (currentModel.getType() != 100) {
                videoListView.setOnBackground(false);
            } else {
                videoListView.setOnBackgroundAD(false);
            }
        } else {
            videoListView.setOnBackground(false);
        }
    }

    public void onStop() {
//        mLoadingView.cancle();
    }

    public void onPause() {
        if (mVideoAdapter != null && mVideoAdapter.getCurrentHolder() != null && mVideoAdapter.getCurrentHolder().getCurrentModel() != null) {
            mVideoAdapter.onPause();
        }
        if (videoListView != null) {
            videoListView.setOnBackground(true);
        }
    }

    public boolean isOnBackground() {
        if (videoListView != null) {
            videoListView.isOnBackground();
        }
        return true;
    }

    public void onDestroy() {
        context = null;
    }

    /**
     * 视频列表获取失败
     */
    public void loadFailure() {
//        mLoadingView.cancle();
        videoListView.loadFailure();
    }


    private FragmentActivity mActivity;

    private FragmentManager getFragmentManager() {
        FragmentManager fm = null;
        if (mActivity != null) {
            fm = mActivity.getSupportFragmentManager();
        } else {
            Context mContext = getContext();
            if (mContext instanceof FragmentActivity) {
                fm = ((FragmentActivity) mContext).getSupportFragmentManager();
            }
        }
        return fm;
    }

    /**
     * 刷新sts信息
     *
     * @param tokenInfo
     */
    public void refreshStsInfo(StsTokenInfo tokenInfo) {
    }

    //点击红心
    public void onHartClick() {
        if (mVideoAdapter != null && mVideoAdapter.getDataList() != null && mVideoAdapter.getDataList().size() > 0 && videoListView != null) {
            mVideoAdapter.onHearClick(mVideoAdapter.getDataList().get(videoListView.getCurrentPosition()));
        }

    }

    float dx;
    float dy;

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                dx = event.getX();
                dy = event.getY();
                break;
            case MotionEvent.ACTION_UP:
                float disX = dx - event.getX();
                float disY = dy - event.getY();
                if (disX > 60 && disX > Math.abs(disY) + 20) {
                    toFriendInfo();
                }
                break;
        }
        return super.dispatchTouchEvent(event);
    }

    private void toFriendInfo() {
        BaseVideoSourceModel source = getCurrentModel();
        if (source != null && source.getUser() != null) {
            try {
                String userId = source.getUser().getUserId();
                Intent intent = new Intent(context, FriendsDetailsActivity.class);
                intent.putExtra("USER_ID", userId);
                context.startActivity(intent);
                ((Activity) context).overridePendingTransition(com.zf.shuashua.R.anim.right_in, com.zf.shuashua.R.anim.left_out);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void start() {
        if (mPlayProgressBar != null) {
            mPlayProgressBar.setVisibility(GONE);
        }
    }

    public void stop() {
        if (mPlayProgressBar != null) {
            mPlayProgressBar.setVisibility(GONE);
        }
    }

    public void onCompletion() {
        if (mPlayProgressBar != null) {
            mPlayProgressBar.setVisibility(GONE);
        }
    }

    public void playNext() {
        if (videoListView != null) {
            videoListView.playNext();
        }
    }

    public void playAd() {
        if (videoListView != null) {
            videoListView.playAd();
        }
    }

    /**
     * 删除按钮点击listener
     */
    public interface OnVideoDeleteListener {
        /**
         * 删除视频
         *
         * @param videoId 视频id
         */
        void onDeleteClick(LittleMineVideoInfo.VideoListBean videoId);
    }

    public void setOnVideoDeleteListener(
            OnVideoDeleteListener mOutOnVideoDeleteListener) {
        this.mOutOnVideoDeleteListener = mOutOnVideoDeleteListener;
    }

    public interface OnItemClickListener {
        void onJumpComment(String videoId, String headerUrl, int commentCount, int position);

        void onJumpShare();

        void onJumpAdDetail(String link_type, String url);

        void onAdPlayStart();

        void onAdPlayPaused();

        void onAdPlayComplete();
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.mOnClickListener = listener;
    }

    /**
     * 移除当前播放的视频
     */
    public void removeCurrentPlayVideo() {
        videoListView.removeCurrentPlayVideo();
    }

    public void setOnPlayStatusListener(AlivcVideoListView.OnPlayStatusListener listener) {
        if (videoListView != null) {
            videoListView.setOnPlayStatusListener(listener);
        }
    }

    public AlivcVideoListView.OnPlayStatusListener getOnPlayStatusListener() {
        return videoListView.getOnPlayStatusListener();
    }


    public void setOnAdStatusListener(AlivcVideoListView.OnAdStatusListener listener) {
        if (videoListView != null) {
            videoListView.setOnAdListener(listener);
        }
    }

    public AlivcVideoListView.OnAdStatusListener getOnAdStatusListener() {
        return videoListView.getOnAdListener();
    }


    public void performShareClick() {
        if (videoListView != null) videoListView.performShareClick();
    }

    public void autoPraise() {
        if (videoListView != null) videoListView.autoPraise();
    }

    /**
     * 通过事件更新评论数量
     */
    public void updateCommentNumber(String videoId, int commentNum, int position) {
        if (mVideoAdapter != null && mVideoAdapter.getDataList().size() > position) {
            // 刷新方式会导致视频暂停播放
            BaseVideoSourceModel model = mVideoAdapter.getDataList().get(position);
            if ((model.getId() + "").equals(videoId)) {
                model.setCommentCount(commentNum);
                // mVideoAdapter.notifyItemChanged(position);
            }
        }
    }

}
